package com.lw.leetcode.arr.b;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * 384. 打乱数组
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/22 9:27
 */
public class Solution3 {

    private int[] nums;
    private int[] original;
    private Random random = new Random();
    private int length;

    public Solution3(int[] nums) {
        this.nums = nums;
        this.length = nums.length;
        this.original = new int[nums.length];
        System.arraycopy(nums, 0, original, 0, length);
    }

    public int[] reset() {
        System.arraycopy(original, 0, nums, 0, length);
        return nums;
    }

    public int[] shuffle() {
        int[] shuffled = new int[length];
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < length; ++i) {
            list.add(nums[i]);
        }
        for (int i = 0; i < length; ++i) {
            int j = random.nextInt(list.size());
            shuffled[i] = list.remove(j);
        }
        System.arraycopy(shuffled, 0, nums, 0, length);
        return nums;
    }

}
